package com.elite.groovy.davco.init;

import com.elite.groovy.davco.init.initClinkReport;
import com.elite.groovy.kh.KHUtil;
import com.elite.groovy.kh.TxConfig;
import com.elite.groovy.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @projectName: Degao_Clink
 * @package: com.elite.groovy.davco.clink
 * @className: SignUtil
 * @description: TODO
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */
public class initGetYPSMS {
    private static final Log log = LogFactory.getLog(initClinkReport.class);
    private static Map<String, String> headMap = new HashMap<String, String>();
    private static boolean isRun = true;

    public static void main(String[] args) throws Exception {
        // 创建日期格式对象并设置要输出的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        try {

            // 获取数据源
            JdbcTemplate jt = new JdbcTemplate(TxConfig.getDruidDataSource());

            // 同步IB呼入数据
            int Offset = 1;
            isRun = true;
            log.debug("获取云片短信发送历史...");
            while (isRun && Offset < 1000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("获取云片短信发送历史...偏移Offset:" + Offset);
                toDoSMSGet(jt, "2024-01-01 00:00:00", "2024-02-01 00:00:00", Offset);
                Offset = Offset + 1;
            }

            log.debug("获取云片短信发送历史 结束执行...");
        } catch (Exception e) {
            log.error("HTTP请求调用错误，接口处理异常：" + e.getMessage());

        }

    }

    // 1-获取云片短信发送历史
    public static void toDoSMSGet(JdbcTemplate jt, String StartTime, String EndTime, int Offset) throws Exception {

        Map<String, String> paramHashMap = new HashMap<String, String>();
        paramHashMap.put("apikey", "58778defa73e383a742e24c153b84096");
        paramHashMap.put("start_time", StartTime);
        paramHashMap.put("end_time", EndTime);
        paramHashMap.put("page_num", String.valueOf(Offset));
        paramHashMap.put("page_size", "100");

        String injson = SplicingMap(paramHashMap, "&");
        log.debug("获取云片短信发送历史 待发送参数信息:" + injson);

        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/x-www-form-urlencoded");
        Date date2 = new Date();
        String resTokenJson = Util.doHttpPostUseHead("https://sms.yunpian.com/v2/sms/get_record.json", injson, "UTF-8", 10000, 0, headMap);
        log.debug("获取云片短信发送历史 resTokenJson: " + resTokenJson);

        JSONArray sms_JSONArray = JSONArray.fromObject(resTokenJson);
        log.debug("获取云片短信发送历史 结果:" + sms_JSONArray);

        if (sms_JSONArray.size() < 100) {
            isRun = false;
        }

        for (int i = 0; i < sms_JSONArray.size(); i++) {

            JSONObject sms_Json = sms_JSONArray.getJSONObject(i);
            String sid = KHUtil.GetSFJV(sms_Json, "sid");
            String mobile = KHUtil.GetSFJV(sms_Json, "mobile");
            String send_time = KHUtil.GetSFJV(sms_Json, "send_time");
            String text = KHUtil.GetSFJV(sms_Json, "text");
            String send_status = KHUtil.GetSFJV(sms_Json, "send_status");
            String report_status = KHUtil.GetSFJV(sms_Json, "report_status");
            String fee = KHUtil.GetSFJV(sms_Json, "fee");
            String user_receive_time = KHUtil.GetSFJV(sms_Json, "user_receive_time");
            String error_msg = KHUtil.GetSFJV(sms_Json, "error_msg");
            String uid = KHUtil.GetSFJV(sms_Json, "uid");

            String selectSQL = "Select Documentout_Guid From Documentout Where 1 = 1";
            List<Map<String, Object>> selectList = null;
            if (!KHUtil.isNull(uid)) {
                selectList = jt.queryForList(selectSQL + " And Uid = ?", uid);
            } else {
                selectList = jt.queryForList(selectSQL + " And MsgID = ?", sid);

            }

            if (selectList.size() <= 0) {
                String updateSQL = "Insert Into Documentout (Documentout_Guid, Doctype, Status, Trialcount, Trialcountlimit, Documentfrom, Documentto, Documentpath, Comments, Priority_Id, Expectedstartdate, Lasttrydatetime, Finishdatetime, Createdby, Createddate, Modifiedby, Modifieddate, MsgID, Uid, Report_Status, User_Receive_Time, Error_Detail, Synchronize_Time, Sub_Doctype) Values (Uuid(), 3, 1, 1, 3, 'IVR', ?, ?, ?, '0', ?, ?, ?, 'SELITE', ?, 'SELITE', Now(), ?, ?, ?, ?, ?, Now(), 'IVR')";

                jt.update(updateSQL, mobile, text, "IVR", send_time, send_time, send_time, send_time, sid, uid, report_status, user_receive_time, error_msg);

            }

        }
    }

    // 参数处理
    public static String SplicingMap(Map<String, String> param, String Splicing) {
        TreeMap<String, String> paramTreeMap = new TreeMap<>(param);
        String prestr = "";
        for (Map.Entry<String, String> vo : paramTreeMap.entrySet()) {
            vo.getKey();
            vo.getValue();
            prestr = prestr + Splicing + vo.getKey() + "=" + vo.getValue();
        }
        prestr = prestr.substring(1);
        return prestr;
    }

}